package org.wangblue.document;

import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.wangblue.common.Client;

import java.io.IOException;

/**
 * @Description: 批量新增文档
 * @Author: WangBlue
 * @Create: 2024-10-24 10:27
 * @Version: 1.0
 **/

public class BatchAddDocument {
    private static final String INDEX_NAME = "user";
    public static void main(String[] args) throws IOException {
        try (RestHighLevelClient client = Client.getClient()) {
            // 创建批量新增请求对象
            BulkRequest request = new BulkRequest();
            request.add(
                    new IndexRequest().index(INDEX_NAME).id("1001")
                            .source(XContentType.JSON, "name", "张三", "sex", "男", "age", "18")
            );
            request.add(
                    new IndexRequest().index(INDEX_NAME).id("1002")
                            .source(XContentType.JSON, "name", "李四", "sex", "男", "age", "20")
            );
            request.add(
                    new IndexRequest().index(INDEX_NAME).id("1003")
                            .source(XContentType.JSON, "name", "王五", "sex", "女", "age", "28")
            );
            request.add(
                    new IndexRequest().index(INDEX_NAME).id("1004")
                            .source(XContentType.JSON, "name", "刘六", "sex", "女", "age", "30")
            );

            request.add(
                    new IndexRequest().index(INDEX_NAME).id("1004")
                            .source(XContentType.JSON, "name", "钱七", "sex", "男", "age", "25")
            );

            // 客户端发送请求，获取响应对象
            BulkResponse responses = client.bulk(request, RequestOptions.DEFAULT);

            // 打印结果信息
            System.out.println("took:" + responses.getTook());
            if (responses.hasFailures()) {
                System.out.println("Failures: " + responses.buildFailureMessage());
            } else {
                System.out.println("All documents added successfully!");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
